package com.sky.handler;

import com.sky.constant.MessageConstant;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.BaseException;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获 具体的业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        //Duplicate entry 'zhangsan' for key 'employee.idx_username'
        log.error("异常信息：{}", ex.getMessage());
        String message = ex.getMessage();
        if (message.contains("Duplicate entry")){
        String[] split = message.split(" ");
        String errorMessage = split[2] + MessageConstant.ALREADY_EXISTS;
        return Result.error(errorMessage);}
        else return Result.error("未知的异常~");
    }

//    @ExceptionHandler
    public Result AccountNotFoundExceptionhander(AccountNotFoundException accountNotFoundException)
    {
        log.error(accountNotFoundException.getMessage());
        String message = accountNotFoundException.getMessage();
        return Result.error(message);
    }



@ExceptionHandler
    public Result Exceptionhander(Exception exception)
    {
        log.error(exception.getMessage());
        String message = exception.getMessage();
        exception.printStackTrace();
            return Result.error(message);}
}
